package mess;

public class LeeCode_21_2 {
    public static void main(String[] args) {
        ListNode l1 = new ListNode(1, new ListNode(2, new ListNode(4)));
        ListNode l2 = new ListNode(1, new ListNode(3, new ListNode(4)));
        System.out.println(mergeTwoLists(l1, l2));
        ListNode l3 = null;
        ListNode l4 = new ListNode(0);
        System.out.println(mergeTwoLists(l3, l4));
        System.out.println("-------------");
        ListNode l5 = new ListNode(2);
        ListNode l6 = new ListNode(1);
        System.out.println(mergeTwoLists(l5, l6));
    }

    private static ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        ListNode result = new ListNode(0);
        ListNode cur = result;
        while (list1 != null && list2 != null){
            if (list1.val <= list2.val){
                cur.next = list1;
                cur = cur.next;
                list1 = list1.next;
            }else {
                cur.next = list2;
                cur = cur.next;
                list2 = list2.next;
            }
        }
        if (list1 == null)
            cur.next = list2;
        else
            cur.next = list1;
        return result.next;
    }

    private static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }

        @Override
        public String toString() {
            return this.val + "->" + this.next;
        }
    }
}
